package com.wxdc.nmgyt.nmgytwydc.activity;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.ActionBar;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.StaggeredGridLayoutManager;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.MenuItem;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import com.wxdc.nmgyt.nmgytwydc.R;
import com.wxdc.nmgyt.nmgytwydc.adapter.PhotoData_RecyclerViewAdapter;
import com.wxdc.nmgyt.nmgytwydc.app.MyApp;
import com.wxdc.nmgyt.nmgytwydc.common.CustomDialog;
import com.wxdc.nmgyt.nmgytwydc.greendao.CbYfWzInfoBeanDao;
import com.wxdc.nmgyt.nmgytwydc.greendao.ope.CbYfInfoBeanDaoOpe;
import com.wxdc.nmgyt.nmgytwydc.greendao.ope.CbYfWzInfoBeanDaoOpe;
import com.wxdc.nmgyt.nmgytwydc.greendao.ope.YdInfoBeanDaoOpe;
import com.wxdc.nmgyt.nmgytwydc.model.CommitDataBean;
import com.wxdc.nmgyt.nmgytwydc.model.PicUploadStateBean;
import com.wxdc.nmgyt.nmgytwydc.presenter.PhotoUploadPersenter;
import com.wxdc.nmgyt.nmgytwydc.presenter.contract.PhotoUploadContract;
import com.wxdc.nmgyt.nmgytwydc.utils.FileUtil;
import com.wxdc.nmgyt.nmgytwydc.utils.Network;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import okhttp3.ResponseBody;

/**
 * Created by Administrator on 2018/6/5.
 */

public class PhotoActivity extends BaseActivity<PhotoUploadPersenter> implements PhotoUploadContract.View {
    private final String TAG = this.getClass().getSimpleName();
    @BindView(R.id.toolbar_title)
    TextView mToolbarTitle;
    @BindView(R.id.toolbar)
    Toolbar mToolbar;
    @BindView(R.id.photo_recycleview)
    RecyclerView mPhotoRecycleview;
    @BindView(R.id.toolbar_upload_pic_imgv)
    ImageView mToolbarUploadPicImgv;
    private List<String> urls;
    private PhotoData_RecyclerViewAdapter mAdapter;
    private CommitDataBean mCommitDataBean;
    private final String ACCEPTVALUE = "acceptData";
    private CustomDialog mCustomDialog;
    @Override
    protected int getLayout() {
        return R.layout.activity_photo;
    }

    @Override
    protected void initInject() {
        getActivityComponent().Inject(this);
    }

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        this.setSupportActionBar(mToolbar);
        mToolbarTitle.setText(getResources().getString(R.string.photo_activity_title));
        ActionBar actionBar = getSupportActionBar();
        actionBar.setHomeButtonEnabled(true);
        actionBar.setDisplayHomeAsUpEnabled(true);
        actionBar.setTitle("");
        EventBus.getDefault().register(this);//这句话一定不要放在 初始化组件之前

        //设置Recyclerview
        final StaggeredGridLayoutManager layoutManager = new StaggeredGridLayoutManager(3,StaggeredGridLayoutManager.VERTICAL);//定义瀑布流管理器，第一个参数是列数，第二个是方向。
        layoutManager.setGapStrategy(StaggeredGridLayoutManager.GAP_HANDLING_NONE);//不设置的话，图片闪烁错位，有可能有整列错位的情况。
        mPhotoRecycleview.setLayoutManager(layoutManager);
        mPhotoRecycleview.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
                super.onScrollStateChanged(recyclerView, newState);
                layoutManager.invalidateSpanAssignments();//这行主要解决了当加载更多数据时，底部需要重绘，否则布局可能衔接不上。
            }
        });
        initData();
        updateUI();
    }

    /*
    * demo  测试数据
    * */
    private void initData() {
        urls = new ArrayList<>();
        /*urls.add("/storage/emulated/0/jczApp/photo/IMG_20171113_090949.jpg");
        urls.add("/storage/emulated/0/jczApp/photo/IMG_20171111_151159.jpg");
        urls.add("/storage/emulated/0/DCIM/IMG_20171129_161749.jpg");
        urls.add("/storage/emulated/0/DCIM/IMG_20171129_161749.jpg");
        urls.add("/storage/emulated/0/DCIM/IMG_20171129_161749.jpg");
        */

        if (mCommitDataBean.getYdInfoBean() != null && mCommitDataBean.getYdInfoBean().getIMGPATH() != null) {
            String[] ydPics =  mCommitDataBean.getYdInfoBean().getIMGPATH().split(",");
            int len = ydPics.length;
            for (int i = 0 ; i < len; i++) {
                urls.add(ydPics[i]);
            }
        }
        if (mCommitDataBean.getCbYfInfoBeanList() != null) {
            int cbNums = mCommitDataBean.getCbYfInfoBeanList().size();
            for (int i = 0 ; i< cbNums; i++) {
               /* Log.i(TAG, "initData: ----------->"+mCommitDataBean.getCbYfInfoBeanList().get(i).getIMGPATH());
                if (mCommitDataBean.getCbYfInfoBeanList().get(i).getIMGPATH() != null && !mCommitDataBean.getCbYfInfoBeanList().get(i).getIMGPATH().isEmpty() && mCommitDataBean.getCbYfInfoBeanList().get(i).getISUPLOADPIC()==0) {
                    if (mCommitDataBean.getCbYfInfoBeanList().get(i).getIMGPATH().lastIndexOf(",") == -1) {
                        break;
                    }
                    urls.add(mCommitDataBean.getCbYfInfoBeanList().get(i).getIMGPATH().substring(0,mCommitDataBean.getCbYfInfoBeanList().get(i).getIMGPATH().lastIndexOf(",")));
                }*/
                /*if (mCommitDataBean.getCbYfInfoBeanList().get(i).getWzInfos() != null) {
                    int cbWzNums = mCommitDataBean.getCbYfInfoBeanList().get(i).getWzInfos().size();
                    for (int j = 0 ; j < cbWzNums ; j++) {
                        if (mCommitDataBean.getCbYfInfoBeanList().get(i).getWzInfos().get(j).getYSZPICURL() != null && !mCommitDataBean.getCbYfInfoBeanList().get(i).getWzInfos().get(j).getYSZPICURL().isEmpty() && mCommitDataBean.getCbYfInfoBeanList().get(i).getWzInfos().get(j).getISUPLOADPIC() == 0) {
                            urls.add(mCommitDataBean.getCbYfInfoBeanList().get(i).getWzInfos().get(j).getYSZPICURL());
                        }
                    }
                }*/
            }
        }
    }

    /*
    * 更新UI
    * */
    private void updateUI() {
        if (mAdapter == null) {
            mAdapter = new PhotoData_RecyclerViewAdapter(mContext, urls);
            mPhotoRecycleview.setAdapter(mAdapter);
            mAdapter.setItemListener(new PhotoData_RecyclerViewAdapter.PhotoDataRecyclerViewListener() {
                @Override
                public void onClickListener(int position) {
                    EventBus.getDefault().postSticky(urls);
                    PhotoViewActivity.startActivity(mContext, urls.get(position));
                }
            });
        }
    }

    /*
    * 打开当前activity
    * */
    public static void startActivity(Context context) {
        Intent intent = new Intent(context, PhotoActivity.class);
        context.startActivity(intent);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        int selectedID = item.getItemId();
        switch (selectedID) {
            case android.R.id.home:
                finish();
                break;
        }
        return super.onOptionsItemSelected(item);
    }

    @Override
    public void showError(String msg) {
        mApp.showToastLongMessage(mContext,msg);
        mCustomDialog.hideDialog();
    }

    @OnClick(R.id.toolbar_upload_pic_imgv)
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.toolbar_upload_pic_imgv:
                Log.i(TAG, "onViewClicked: ------------------>上传图片" + urls);
                if (!Network.isConnected(mContext)) {
                    mApp.showToastLongMessage(mContext,getResources().getString(R.string.no_network));
                    return;
                }
                if (mCustomDialog == null) {
                    mCustomDialog = new CustomDialog(mContext, "图片上传中...");
                }
                mCustomDialog.showDialog();
                upLoadPhotoFunc();
                break;
        }
    }

    /*
    * 图片上传返回结果
    * */
    @Override
    public void photoUploadResult(PicUploadStateBean result) {
       /* if (result != null && "1".equals(result.get(0).getState())) {//上传成功
            urls.remove(photoNum - 1);
            String picName = result.get(0).getName();
            String picNameFlag = picName.substring(picName.lastIndexOf(".")-1,picName.lastIndexOf("."));
            mAdapter.notifyDataSetChanged();
            //图片上传服务器之后，将数据库中ISUPLOADPIC设置为1"
            if (mCommitDataBean.getYdInfoBean() != null && mCommitDataBean.getYdInfoBean().getIMGPATH() != null) {//样地信息调查表中查找
                *//*if (picName.contains("JG") && "E".equals(picNameFlag)) {
                    mCommitDataBean.getYdInfoBean().setIMGNAME_E(picName);
                } else if (picName.contains("JG") && "S".equals(picNameFlag)) {
                    mCommitDataBean.getYdInfoBean().setIMGNAME_S(picName);
                }else if (picName.contains("JG") && "W".equals(picNameFlag)) {
                    mCommitDataBean.getYdInfoBean().setIMGNAME_W(picName);
                }else if (picName.contains("JG") && "N".equals(picNameFlag)) {
                    mCommitDataBean.getYdInfoBean().setIMGNAME_N(picName);
                }
                mCommitDataBean.getYdInfoBean().setISUPLOADPIC(1);*//*
                YdInfoBeanDaoOpe.updateData(mContext,mCommitDataBean.getYdInfoBean());
            }
            if (mCommitDataBean.getCbYfInfoBeanList() != null && result.get(0).getName().contains("YF")) {
                int cbNums = mCommitDataBean.getCbYfInfoBeanList().size();
                for (int i = 0 ; i< cbNums; i++) {
                   *//* if (mCommitDataBean.getCbYfInfoBeanList().get(i).getIMGPATH() != null && mCommitDataBean.getCbYfInfoBeanList().get(i).getIMGPATH().contains(picName)) {
                        mCommitDataBean.getCbYfInfoBeanList().get(i).setISUPLOADPIC(1);
                        mCommitDataBean.getCbYfInfoBeanList().get(i).setIMGNAME(picName);
                        CbYfInfoBeanDaoOpe.updateData(mContext,mCommitDataBean.getCbYfInfoBeanList().get(i));
                    }*//*
                    *//*if (mCommitDataBean.getCbYfInfoBeanList().get(i).getWzInfos() != null) {
                        int cbWzNums = mCommitDataBean.getCbYfInfoBeanList().get(i).getWzInfos().size();
                        for (int j = 0 ; j < cbWzNums ; j++) {
                            if (mCommitDataBean.getCbYfInfoBeanList().get(i).getWzInfos().get(j).getYSZPICURL() != null) {
                                mCommitDataBean.getCbYfInfoBeanList().get(i).getWzInfos().get(j).setISUPLOADPIC(1);
                                CbYfWzInfoBeanDaoOpe.updateData(mContext,mCommitDataBean.getCbYfInfoBeanList().get(i).getWzInfos().get(j));
                            }
                        }
                    }*//*
                }
            }
            //
            upLoadPhotoFunc();
        } else if (result != null && "0".equals(result.get(0).getState())) {
            mApp.showToastLongMessage(mContext,"上传失败");
        }*/

    }
    private int photoNum;
    private String curtPhotoAddress;
    private void upLoadPhotoFunc() {
        photoNum = urls.size();
        if (photoNum > 0) {
            mPersenter.photoUpload(urls.get(photoNum - 1));
            curtPhotoAddress = urls.get(photoNum - 1);
        } else {
            mCustomDialog.hideDialog();
        }
    }

    /*
    *
    * */
    @Subscribe(threadMode = ThreadMode.MAIN, sticky = true)
    public void dataEvent(CommitDataBean infoBean) {
        mCommitDataBean = infoBean;
        Log.i(TAG, "dataEvent: --------------------------->"+mCommitDataBean);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().unregister(this);
        }
    }
}
